# cython: language_level=3
import os
import time

from dotenv import load_dotenv
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from app.db.sql.resource import get_real_time_data
from app.middlewares.redis import get_redis
from app.schemas.platform import TimeSynRequest, SendRealTimeDataRequest
from common.database import get_db
from common.http import ok_response, error_response
from common.redis import MyRedis
# 将一组接口归为这个大标签下
router = APIRouter(tags=["platform-routine"])
router.prefix = "/v2"
load_dotenv()
CREDIT_CODE = os.getenv("CREDIT_CODE")


@router.post("/timeSyn")
def time_sync(paylad: TimeSynRequest):
    """
    2.9
    终端通过对时接口将时标发送给南向服务器，南向服务器拿到时标后设置服务器时标。
    """
    # set the time of the server
    timescale = float(paylad.timescale)
    timescale /= 1000
    time.clock_settime(time.CLOCK_REALTIME, timescale)
    return ok_response([])


@router.post("/sendRealTimeData")
def send_real_time_data(
        payload: SendRealTimeDataRequest,
        db: Session = Depends(get_db),
        redis: MyRedis = Depends(get_redis),
):
    """
    2.3
    用户上报实时负荷数据
    """
    if payload.creditCode != CREDIT_CODE:
        return error_response(5000, "creditCode不正确")
    ret_data = get_real_time_data(db, payload, payload.page, payload.pageSize, redis)
    return ok_response(ret_data)
